<template>
  <div class="myDiv">
    <Newcard title="收银台" :isScroll="true" :isright="true">
      <!-- 超时支付说明 -->
      <div class="time_intro" slot="right">
        请在 {{ minute }}:{{ second }} 内完成支付,超时订单自动取消
      </div>
      <!-- 主体内容 -->
      <div class="myDiv_content">
        <div class="content_int flex flex_fc flex_jc">
          <div class="m_b_12"><b>智慧文控</b></div>
          <div>份数单价： {{ unitPrice || 0 }}/份</div>
          <div>应付金额： {{ price }}.00</div>
        </div>
        <div class="contrac_button m_t_38">
          <b>合同份数</b>
          <div class="contrac_button_box flex flex_ac m_t_16">
            <el-input-number
              v-model="payNum"
              :disabled="isTrial"
              :step="5"
              step-strictly
              :min="5"
              @change="changeNum"
            ></el-input-number>
          </div>
        </div>
        <div class="person_info m_t_38">
          <b>实购人</b>
          <div class="m_t_16">
            <!-- --------------选择实购人-------------- -->
            <div class="joinIn">
              <div class="selectCircleAvi" v-if="circleAvi.userId">
                <img :src="circleAvi.avatar || DefaultAvavter" alt="" />
                <p>
                  {{ rulName(circleAvi.nickname) }}({{ circleAvi.phonenumber }})
                </p>
                <i class="el-icon-error" @click="removeCircleAvi"></i>
              </div>
              <el-input
                v-else
                v-model="circleAvi.phone"
                maxlength="11"
                placeholder="请输入手机号码"
                @focus="showjoinInput"
                @input="changejoinPhone"
              ></el-input>
              <!-- 查询手机号弹出框 -->
              <div class="myAskSelect" :class="joinInShow ? 'joinInShow' : ''">
                <ul>
                  <template v-if="circleList.length > 0">
                    <li
                      v-for="item in circleList"
                      :key="item.id"
                      @click="selectJoinIn(item)"
                    >
                      <img :src="item.avatar || DefaultAvavter" alt="" />
                      <div>
                        <h3>
                          {{ item.phonenumber }} {{ rulName(item.nickname) }}
                        </h3>
                      </div>
                    </li>
                  </template>
                  <div v-else>暂无成员</div>
                </ul>
              </div>
              <!-- 查询手机号弹出框 end -->
            </div>
            <!-- --------------选择实购人end-------------- -->
          </div>
        </div>
        <div class="pay_info m_t_38">
          <b>选择支付方式</b>
          <el-row :gutter="10" class="m_t_16">
            <el-col :span="24">
              <div
                class="pay_type_box"
                :class="type == 0 ? 'pay_ac' : 'pay_dc'"
                @click="changeType(0)"
              >
                问金支付
              </div>
            </el-col>
            <!-- <el-col :span="8">
              <div
                class="pay_type_box"
                :class="type == 1 ? 'pay_ac' : 'pay_dc'"
                @click="changeType(1)"
              >
                扫码支付
              </div>
            </el-col>
            <el-col :span="8">
              <div
                class="pay_type_box"
                :class="type == 2 ? 'pay_ac' : 'pay_dc'"
                @click="changeType(2)"
              >
                转账支付
              </div>
            </el-col> -->
          </el-row>
          <div v-if="type == 0">
            <div class="person_list">
              <div
                class="person_list_item flex flex_js"
                v-for="(item, index) in personList"
                :key="item.userId"
              >
                <div class="flex" :class="item.share ? 'opac' : ''">
                  <div class="header">
                    <el-image
                      class="header"
                      :src="
                        item.avatar ||
                        require('@/assets/images/defaultAvatar.jpg')
                      "
                    ></el-image>
                  </div>
                  <div class="item_info">
                    <div>{{ item.nickname }}</div>
                    <span v-if="item.balance || isTrial "
                      >余额：{{ item.balance || 0}}问金</span
                    >
                    <span v-else>余额不足,请充值</span>
                  </div>
                </div>

                <el-checkbox
                  class="checkBox"
                  v-model="item.defaultPay"
                  :disabled="(item.balance < price || !item.balance) && !isTrial"
                  :checked="getCheck(item.defaultPay)"
                  true-label="1"
                  false-label="0"
                  @change="handleChange(index)"
                ></el-checkbox>
              </div>
            </div>
          </div>
          <div class="m_t_16" v-else-if="type == 2">
            <div class="pay_info_content">
              <span>收款账号：</span>
              <span>7699 0764 7210 808</span>
            </div>
            <div class="pay_info_content">
              <span>收款户名：</span>
              <span>东莞叁师科技有限公司 </span>
            </div>
            <div class="pay_info_content">
              <span>开户银行：</span>
              <span>招商银行股份有限公司东莞恒大雅苑支行</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部菜单 -->
      <div class="myDiv_foot flex flex_ac flex_js">
        <div>
          <b>应付金额：</b><span class="myDiv_foot_price">{{ price }}.00</span>
        </div>
        <div class="submit" @click="submit" v-if="type == 0">确认付款</div>
        <div class="submit" v-else>我已打款</div>
      </div>
    </Newcard>
  </div>
</template>

<script>
import Newcard from "@/wss/components/newCard.vue";
import {
  getPrice,
  selectCircleAmount,
  mobileCircleAmount,
  addOrder,
  voucherPay,
  getAddOrderTryApi,
} from "@/BMViews/api/intelligentControl/intelligentControl.js";
import {getProjectOrderGetInfoApi} from "@/BMViews/api/budget/budgetService.js"
import {addProjectApi} from "@/BMViews/api/doc/project.js"
import Compay from "@/BMViews/components/Compay/index.vue";
import debounce from "lodash/debounce";
export default {
  components: {
    Newcard,
    Compay,
  },
  props: {
    isTrial: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    circleInfo:{
      type:Object,
      default:{}
    }
  },
  data() {
    return {
      type: 0, //支付类别判断
      minute: 15,
      second: 0,
      payNum: 20, //份数
      price: 0, //份数价格
      unitPrice: 0,

      personList: [], //支付问圈角色
      circleList: [], //实付人列表
      useremail: this.$store.state.user.email,
      joinInShow: false, // 邀请成员的弹出框显示隐藏
      isUnfold: false, // 邀请成员是否显示
      circleAvi: {}, //默认选中的问圈角色
      DefaultAvavter: require("@/assets/images/defaultAvatar.jpg"), //默认头像
    };
  },
  watch: {
    price(newValue) {
      this.unitPrice = newValue / this.payNum;
    },
    second: {
      handler(newVal) {
        this.num(newVal);
      },
    },
    minute: {
      handler(newVal) {
        this.num(newVal);
      },
    },
    // 监听是否试用
    isTrial(newValue) {
      if (newValue) {
        this.payNum = 10;
        this.price = 0;
      } else {
        this.payNum = 20;
        this.getPrice(); // 获取默认的价格
      }
    },
  },
  computed: {},
  methods: {
    // 更改份数
    changeNum(e){
      console.log(e);
      this.getPrice()
    },
    // ----------------------------------实购人----------------------------------
    // 显示弹出框
    showjoinInput() {
      this.joinInShow = true;
    },
    // 隐藏弹出框
    hidejoinInput() {
      // this.joinInShow = false
    },

    // 清除选择
    removeCircleAvi() {
      this.joinInShow = true;
      this.circleAvi = {};
    },

    // 过滤实购人
    changejoinPhone() {
      let phone = this.circleAvi.phone;
      if (phone) {
        this.circleList = JSON.parse(JSON.stringify(this.personList));
      }

      this.circleList = this.circleList.filter((item) => {
        return item.phonenumber.includes(phone);
      });
    },

    // 选择一条问圈
    selectJoinIn(item) {
      this.circleAvi = item;
      this.joinInShow = false;
    },

    //获取我的问圈
    async selectCircleAmount() {
      let data = {
        myself: true,
      };
      let result = await selectCircleAmountApi(data);
      if (result.code == 200) {
        this.circleList = result.rows;
        this.personList = JSON.parse(JSON.stringify(result.rows));

        this.circleList.forEach((item) => {
          if (item.defaultPay == 1) {
            this.circleAvi = item;
          }
        });
      }
    },

    // 去掉‘的问圈’，并且只显示名字最后一个字
    rulName(name) {
      let reg = new RegExp("的圈子", "g");
      let rulName = name.replace(reg, "");
      // return new Array(rulName.length).join("*") + rulName.substr(-1);
      return rulName;
    },
    num(n) {
      return n < 10 ? "0" + n : "" + n;
    },
    //倒计时
    countdown() {
      var _this = this;
      var time = window.setInterval(function () {
        if (_this.second === 0 && _this.minute !== 0) {
          _this.second = 59;
          _this.minute -= 1;
        } else if (_this.minute === 0 && _this.second === 0) {
          _this.second = 0;
          window.clearInterval(time);
          changes();
        } else {
          _this.second -= 1;
        }
      }, 1000);
    },
    // 获取默认选中状态
    getCheck(e) {
      return e == 1 ? true : false;
    },
    changeType(e) {
      this.type = e;
    },
    // 更换支付人
    handleChange(e) {
      this.personList.forEach((item, index) => {
        if (index != e) {
          item.defaultPay = 0;
        }
      });
    },
    // 获取份数价格
    getPrice: debounce(async function () {
      const res = await getPrice({
        fileNum: this.payNum,
      });
      if (res.code == 200) {
        this.price = res.data;
      }
    }, 300),
    // 获取问圈角色
    async selectCircleAmount() {
      const res = await selectCircleAmount({
        myself: true,
      });
      if (res.code == 200) {
        this.personList = res.rows;
      }
    },
    // 获取问圈角色
    async mobileCircleAmount() {
      const res = await mobileCircleAmount({
        myself: true,
      });
      if (res.code == 200) {
        this.circleList = res.rows;
      }
    },

    submit: debounce(async function () {
      // 邮箱不能为空
      if (!this.circleAvi.userId) {
        this.$message({ type: "warning", message: "请选择实购人" });
        return;
      }
      let obj = this.personList.filter((item) => {
        if (item.defaultPay == 1) {
          return item;
        }
      });
      if (obj.length <= 0) {
        this.$message({
          message: "请选择支付人",
          type: "warning",
        });
        return;
      }
      let res = {}
      if (this.isTrial) {
        // 试用下单
         res = await getAddOrderTryApi({
          adminId: this.circleAvi.userId, //实购人id
          fileNum: this.payNum,
        });
      } else {
        // 购买下单
        res = await addOrder({
          adminId: this.circleAvi.userId, //实购人id
          fileNum: this.payNum,
        });
      }

      if (res.code == 200) {
        this.orderInfo = res.orderId;
        this.voucherPay(obj);
      }
    }, 300),
    voucherPay: debounce(async function (obj) {
      const res = await voucherPay({
        circleId: obj[0].circleId,
        orderId: this.orderInfo,
      });

      if (res.code == 200) {
        if(!this.circleInfo?.fileNum){
							// 不是添加人数就要下项目
							await this.addProjectFn()
						}
        this.$message({
          message: "支付成功",
          type: "success",
        });
        this.$emit("paySuccess");
      }
    }, 300),
    // -----------------下单阿米巴预算项目并且支付-----------------
			async addProjectFn() {
       
				let project = {
					city: '全国', //城市
					cityCode: 'cn', //城市编码
					type: '智慧文控', //阿米巴预算项目type
					typeId: '321', //阿米巴预算项目id
					userId: this.$store.state.user.userInfo.userId, //用户id
					userName: this.$store.state.user.userInfo.name, //用户名字
					email: this.$store.state.user.userInfo.email, //绑定的邮箱
					title: '智慧文控', //阿米巴预算项目名称
				}
         
				let result = await addProjectApi(project)
				if (result.code == 200) {
					let orderinfo = result
					await this.getProjectType(orderinfo) //获取项目详情
				}
			},
      // 获取项目类别的详细信息
			async getProjectType(orderinfo) {
				let id = orderinfo.orderId //阿米巴预算项目id
				let result = await getProjectOrderGetInfoApi({
					id
				})
				if (result.code == 200) {
					this.projectTypeInfo = result.data
					let flowId = this.projectTypeInfo?.goods?.flows[0]?.id
					await this.projectPay(orderinfo, flowId) // 项目问金支付
				}
			},
      // 项目问金支付
			async projectPay(orderinfo, flowId) {
				// 直接支付 问金支付
				let data = {
					circleId: this.circleAvi.circleId, //当前问圈id
					orderId: orderinfo.orderId, //订单id
					email: this.email, //邮箱
					flowId: flowId, //第一步id
				}
				let res = await voucherPay(data)
				if (res.code != 200) return
			},
      // -----------------下单阿米巴预算项目并且支付-----------------end
  },
  created() {
    this.countdown();

    this.selectCircleAmount();
    this.mobileCircleAmount();
  },
  mounted() {
    if (!this.isTrial) {
      this.getPrice();
    } else {
      this.payNum = 10;
    }
  },
};
</script>
<style lang="scss" scoped>
.flex {
  display: flex;
}
.flex_fc {
  flex-direction: column;
}
.flex_ac {
  align-items: center;
}
.flex_jc {
  justify-content: center;
}
.flex_js {
  justify-content: space-between;
}
.m_b_12 {
  margin-bottom: 12px;
}
.m_t_38 {
  margin-top: 38px;
}
.m_t_16 {
  margin-top: 16px;
}
b {
  font-size: 14px;
}

::v-deep .person_list_item .el-checkbox__inner {
  border-radius: 50%;
}
::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  border-color: #fff;
}
::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
  background-color: #e6e6e6;
  opacity: 0.3;
}

.myDiv {
  height: 100%;
  //   超时说明
  .time_intro {
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 17px;
  }
  //   主体样式
  .myDiv_content {
    position: relative;
    padding: 0 30px;
    box-sizing: border-box;
    .content_int {
      width: 100%;
      height: 120px;
      border: 1px solid #efefef;
      border-radius: 12px;
      padding-left: 20px;
      div:nth-child(n + 2) {
        font-size: 14px;
        color: #999999;
      }
      b {
        font-size: 16px;
        color: #232323;
      }
    }
    // 合同份数
    .contrac_button {
      .contrac_button_box {
        width: 320px;
        height: 44px;
        .el-input-number {
          display: block;
          width: 320px;
        }
        .box_item {
          width: 44px;
          height: 44px;
          line-height: 44px;
          text-align: center;
        }
        div:nth-child(2) {
          flex: 1;
          height: 20px;
          font-size: 14px;
          text-align: center;
          color: #333333;
          border-left: 1px solid #d7d7d7;
          border-right: 1px solid #d7d7d7;
        }
      }
    }

    .pay_info {
      .pay_type_box {
        width: 100%;
        height: 44px;
        font-size: 14px;

        text-align: center;
        line-height: 44px;

        border-radius: 8px;
      }
      .pay_ac {
        background-color: #f1f3ff;
        color: #39486f;
      }
      .pay_dc {
        background-color: #fafafa;
        color: #666666;
      }
      .pay_info_content {
        margin-top: 20px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        span:nth-child(1) {
          color: #666666;
        }
        span:nth-child(2) {
          margin-left: 40px;
          color: #333333;
        }
      }
      .person_list {
        .person_list_item {
          width: 100%;
          height: 70px;
          border-bottom: 1px solid #efefef;
          align-items: center;
          .header {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: gray;
            margin-right: 12px;
          }
          .item_info {
            font-size: 14px;
            color: #232323;
            div {
              margin-bottom: 3px;
            }
            span {
              color: #999999;
              font-size: 12px;
            }
          }
          .checkBox {
            transform: scale(1.5);
          }
        }
      }
    }
  }
  .myDiv_foot {
    position: absolute;
    bottom: 0;
    left: 0;
    padding: 0 30px;
    width: 100%;
    height: 60px;
    border: 1px solid #ecedf0;
    background-color: #fff;
    z-index: 9;
    .myDiv_foot_price {
      color: #f87a23;
      font-weight: bold;
    }
    .submit {
      width: 200px;
      height: 40px;
      background: #f87a23;
      border-radius: 20px;
      text-align: center;
      line-height: 40px;
      color: #ffffff;
      font-size: 14px;
    }
  }
}
</style>

<style scoped>
ul,
li,
p,
h3 {
  margin: 0;
  padding: 0;
}

.myDiv >>> .el-card__body {
  position: relative;
}

/* 支付信息 */
.pay {
  margin-top: 15px;
}
.pay_main {
  margin-bottom: 0px;
}
.pay_main .el-card {
  border-radius: 12px;
}
::v-deep .pay_main .el-card__body {
  padding: 20px !important;
}
.pay_main h3 {
  margin: 0;
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}
.pay_main p {
  font-size: 14px;
  color: #999;
  margin: 0;
  line-height: 24px;
}
.pay_main .el-row {
}
::v-deep .pay_main .el-row .el-input__inner {
  border-radius: 8px;
  height: 44px;
  line-height: 44px;
}
.pay_main .el-row .acceptEmail {
  border: 0;
  padding: 5px 0;
  margin: 7px 0;
  margin-right: 10px;
  font-size: 14px;
  color: #bababa;
  background: #fff;
  cursor: pointer;
}
.pay_main .el-row .acceptEmail:hover {
  color: #f87a23;
}
.pay_main .inputTitle {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}
.pay_main .inputTitle span {
  font-size: 14px;
  color: #999;
  font-weight: 400;
}
::v-deep .pay_main .el-tabs__header {
  border: 0;
  margin-bottom: 24px;
}
::v-deep .pay_main .el-tabs__nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
  border: 0;
}
::v-deep .pay_main .el-tabs__item {
  width: 49%;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  border: 0;
  background-color: #fafafa;
}
::v-deep .pay_main .el-tabs__item.is-active {
  background-color: #f1f3ff;
  color: #39486f;
}
::v-deep .pay_main .el-tabs__item:hover {
  color: #39486f;
}

/* 选择实购人 */
.joinIn .el-input {
  width: 320px;
}

.selectCircleAvi {
  width: 320px;
  display: flex;
  align-items: center;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  box-sizing: border-box;
}
.selectCircleAvi img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}
.selectCircleAvi p {
  margin-left: 10px;
}
.selectCircleAvi i.el-icon-error {
  margin-left: auto;
  color: #999;
  cursor: pointer;
}

::v-deep .joinIn .el-input .el-input__inner {
  width: 100%;
  height: 44px;
  line-height: 44px;
}
::v-deep .joinIn .el-input .el-input__inner:focus {
  border-color: #f87a23;
}
.joinIn {
  position: relative;
}
.joinIn .joinBtn {
  width: 100%;
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
  font-weight: bold;
  padding: 14px 20px;
  margin-top: 15px;
}
.joinIn .joinBtn:hover {
  opacity: 0.9;
}

/* 邀请成员弹出框 */
.joinIn .myAskSelect {
  display: none;
  position: absolute;
  left: 3px;
  top: 108%;
  z-index: 9;
  width: 90%;
  padding: 15px;
  border-radius: 12px;
  background-color: #fff;
  box-shadow: 2px 4px 16px 2px rgba(201, 201, 201, 0.5);
}
.joinIn .myAskSelect.joinInShow {
  display: block;
}
.joinIn .myAskSelect > p {
  font-size: 12px;
  font-weight: 400;
  color: #999999;
  margin-bottom: 25px;
}
.joinIn .myAskSelect > p > .el-button {
  border: 1px solid #39486f;
  color: #39486f;
  padding: 4px 10px;
}

.joinIn .myAskSelect > ul {
  max-height: 210px;
  overflow-y: auto;
}
.joinIn .myAskSelect > ul::-webkit-scrollbar {
  width: 0;
}
.joinIn .myAskSelect li {
  display: flex;
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #efefef;
  cursor: pointer;
}
.joinIn .myAskSelect li > img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 15px;
}
.joinIn .myAskSelect li div {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.joinIn .myAskSelect li h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333333;
}
.joinIn .myAskSelect li p {
  font-size: 12px;
  font-weight: 400;
  color: #999;
}
/* 选择实购人 end */
</style>